﻿using System;
using System.Collections.Generic;
using AccessControl.Contracts.Reports;
using AccessControl.Contracts.Models;
using AccessControl.DataManagers;
using AccessControl.Gateway.Managers;
using System.Collections.ObjectModel;

namespace AccessControl.Gateway.Reports
{
	class EventsReports : IEventsReports
	{
		#region Fields

		private static EventsReports s_Instance = null;
		private ObservableCollection<IEvent> _Items = new ObservableCollection<IEvent>();

		#endregion

		#region Private Constructor

		private EventsReports()
		{

		}

		#endregion

		#region Public Properties

		public static EventsReports Instance
		{
			get 
			{
				lock (typeof(EventsReports))
				{
					if (s_Instance == null)
						s_Instance = new EventsReports();

					return s_Instance;
				}
			}
		}

		#endregion

		#region IEventsReports Members

		public bool LoadEvents(DateTime startTime, DateTime endTime)
		{
			Items.Clear();
			return DataManager.Instance.FillList(Items, startTime, endTime);
		}

		public bool LoadEvents(DateTime startTime, DateTime endTime, IList<Contracts.Models.IEntry> entries)
		{
			List<int> sensorIds = new List<int>();

			Items.Clear();
			foreach (IEntry entry in EntriesManager.Instance.Items)
			{
				foreach (IEntry selectedEntry in entries)
				{
					if (entry.Id == selectedEntry.Id)
					{
						foreach (ISensor sensor in entry.Sensors)
						{
							if (!sensorIds.Contains(sensor.Id))
								sensorIds.Add(sensor.Id);
						}
					}
				}
			}

			if (sensorIds.Count == 0)
				return true;

			return DataManager.Instance.FillList(Items, startTime, endTime, sensorIds);
		}

		public IList<IEvent> Items
		{
			get { return _Items; }
		}

		public void Load()
		{
			Items.Clear();
			DataManager.Instance.FillList(Items);
		}

		#endregion
	}
}
